<template>
	<z-paging ref="paging" :refresher-out-rate="0.8" :show-empty-view-reload-when-error="false"
		:empty-view-img-style="{ width: '308rpx', height: '308rpx' }"
		empty-view-error-img="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/12/1c53b8aed0c74201bb092265803a1d48.png"
		empty-view-img="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/12/987eadb1d50949a0a7e25dbbd99abe30.png"
		empty-view-error-text="暂无数据" safe-area-inset-bottom bg-color="#F5F8FE" v-model="dataList" @query="queryList">
		<view slot="top" class="topTabbar">
			<u-tabs :current="currentTab" :list="tabList" @change="tabChange" :scrollable="false"></u-tabs>
		</view>
		<view class="cellBox">
			<view class="flex_wrap fileBox" v-if="currentTab == '0'"><u-icon label="创建权益卡" size="28rpx" name="plus"
					color="#777" labelColor="#777" @click="createShow = true"></u-icon></view>
			<view class="detail" v-for="(item, index) in dataList" :key="index">
				<view class="detail_title">
					<u-text
						prefixIcon="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/03/26/69634380c6b14b678b6a0bf43c6a04ac.png"
						iconStyle="margin-right:16rpx;width:56rpx;height:56rpx" size="36rpx" color="#333" bold
						:text="item.cardType || item.extType" />
					<u-line dashed color="#CCCCCC" margin="20rpx 0 28rpx" />
					<view class="flex_wrap row_between row_bottom">
						<view v-if="currentTab == '0'">
							<u-text color="#777" size="28rpx" :text="`有效期：`+item.validity +`年`" />
							<u-text color="#777" size="28rpx" :text="`推出时间：`+item.createTime" margin="16rpx 0 0" />
						</view>
						<view v-if="currentTab == '1'">
							<u-text color="#777" size="28rpx"
								:text="statusSum[item.type]+(item.number || item.takeNumber) +`张`" />
							<u-text v-if="item.type=='2'" color="#777" size="28rpx"
								:text="`转发渠道：`+ item.channelUserName" margin="16rpx 0 0" />
							<u-text v-if="item.type=='4'" color="#777" size="28rpx"
								:text="'开始时间：'+$u.timeFormat(item.startTime, 'yyyy-mm-dd')" margin="16rpx 0 0" />
							<u-text color="#777" size="28rpx"
								:text="item.type=='4' ? (statusTime[item.type]+ $u.timeFormat(item.endTime, 'yyyy-mm-dd')) : (statusTime[item.type]+ $u.timeFormat(item.createTime, 'yyyy-mm-dd'))"
								margin="16rpx 0 0" />
						</view>
						<view class="flex_wrap" v-if="currentTab == '0' || (currentTab == '1' && item.type=='6')">
							<view :class="currentTab == '0' ? 'btnBox' :'btnBox1'"
								@click="currentTab == '0' ? operate(item) : forward(item)">
								{{currentTab == '0' ? '操作' : '查看' }}
							</view>
							<u-button v-if="currentTab == '1'" text="转发" shape="circle" color="#1682FF"
								:customStyle="buttonCustomStyle" @click="to_shareEX(item)" />
						</view>
						<view v-if="currentTab == '1' && item.type=='4'" @click="qrCode(item)">
							<u-image height="100rpx" width="100rpx"
								src="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/01/10/87f38641d0a6454e8478b0f20c8398a7.png"
								mode="aspectFill" />
						</view>
					</view>
					<view class="cardbg" v-if="currentTab == '0'">{{ item.cardType }}卡</view>
					<view class="cardbgs" v-if="currentTab == '1'" :style="{ background: statusBg[item.type] }">
						{{statusTitle[item.type]}}</view>
				</view>
			</view>
			<u-action-sheet :actions="actionList" @select="selectClick" :closeOnClickOverlay="true"
				:closeOnClickAction="true" @close="actionShow=false" :show="actionShow"
				cancelText="取消"></u-action-sheet>
			<u-modal :show="show" ref="editModal" title="发给渠道" showCancelButton @confirm="confirmEdit"
				@cancel="cancelEdit" confirmText="下一步" confirmColor="#1682FF">
				<view slot="default" style="width: 100%">
					<u--text text="转发人手机号" size="32rpx" color="#3D3D3D" lineHeight="80rpx"></u--text>
					<u--input type="number" placeholder="请输入手机号" :maxlength="11" clearable v-model="phoneNum"
						:customStyle="{
			                            background: '#F7F7F7',
			                            borderRadius: '16rpx 16rpx 16rpx 16rpx',
			                            border: 'none',
			                            height: '80rpx',
			                        }" :placeholderStyle="{
			                            fontSize: '28rpx',
			                            color: '#F7F7F7',
			                        }"></u--input>
				</view>
			</u-modal>
			<u-modal :show="show1" ref="editModal" title="发给渠道" showCancelButton @confirm="confirmEdit1"
				@cancel="cancelEdit1" confirmText="确定" confirmColor="#1682FF" cancelText="上一步">
				<view slot="default" style="width: 100%">
					<u--text text="转发用户" size="32rpx" color="#3D3D3D" lineHeight="80rpx"></u--text>
					<u--input v-model="userNamePhone" disabled :customStyle="{
			                background: '#F7F7F7',
			                borderRadius: '16rpx 16rpx 16rpx 16rpx',
			                border: 'none',
			                height: '80rpx',
			            }" :placeholderStyle="{
			                fontSize: '28rpx',
			                color: '#F7F7F7',
			            }"></u--input>
					<u--text text="转发数量" size="32rpx" color="#3D3D3D" lineHeight="80rpx"></u--text>
					<u--input type="number" placeholder="请输入转发数量" :maxlength="11" clearable v-model="numBer"
						:customStyle="{
			                background: '#F7F7F7',
			                borderRadius: '16rpx 16rpx 16rpx 16rpx',
			                border: 'none',
			                height: '80rpx',
			            }" :placeholderStyle="{
			                fontSize: '28rpx',
			                color: '#F7F7F7',
			            }"></u--input>
				</view>
			</u-modal>
			<!-- 线下印刷 -->
			<u-modal :show="offlineShow" ref="editModal" :title="changeType == '6' ? '线下印刷' : '发给朋友'" showCancelButton @confirm="offlineConfirm"
				@cancel="offlineEdit" confirmText="确定" confirmColor="#1682FF">
				<view slot="default" style="width: 100%">
					<u--text :text="changeType == '6' ? '印刷数量' : '转发数量'" size="32rpx" color="#3D3D3D" lineHeight="80rpx"></u--text>
					<u--input type="number" :placeholder="changeType == '6' ? '请输入印刷数量' : '请输入转发数量'" clearable v-model="offlineNum" :customStyle="{
			                            background: '#F7F7F7',
			                            borderRadius: '16rpx 16rpx 16rpx 16rpx',
			                            border: 'none',
			                            height: '80rpx',
			                        }" :placeholderStyle="{
			                            fontSize: '28rpx',
			                            color: '#F7F7F7',
			                        }"></u--input>
				</view>
			</u-modal>
			<!-- 线上活动 -->
			<u-modal :show="onlineShow" ref="editModal" title="线上活动" showCancelButton @confirm="onlineConfirm"
				@cancel="onlineEdit" confirmText="确定" confirmColor="#1682FF">
				<view slot="default" style="width: 100%">
					<u--text text="开始时间" size="32rpx" color="#3D3D3D" lineHeight="80rpx"></u--text>
					<view class="timeBox">
						<u-text @click="pickerShow = true" :color="startSubmitTime ? '#303133' : '#aaa'" size="30rpx"
							:text="
						        startSubmitTime
						            ? startSubmitTime
						            : '请选择开始时间'
						    " />
					</view>
					<u--text text="结束时间" size="32rpx" color="#3D3D3D" lineHeight="80rpx"></u--text>
					<view class="timeBox">
						<u-text @click="pickerShow2 = true" :color="endSubmitTime ? '#303133' : '#aaa'" size="30rpx"
							:text="
						        endSubmitTime
						            ? endSubmitTime
						            : '请选择结束时间'
						    " />
					</view>
					<u--text text="活动数量" size="32rpx" color="#3D3D3D" lineHeight="80rpx"></u--text>
					<u--input type="number" placeholder="请输入活动数量" clearable v-model="onlineNum" :customStyle="{
			                            background: '#F7F7F7',
			                            borderRadius: '16rpx 16rpx 16rpx 16rpx',
			                            border: 'none',
			                            height: '80rpx',
			                        }" :placeholderStyle="{
			                            fontSize: '28rpx',
			                            color: '#aaa',
			                        }"></u--input>
				</view>
			</u-modal>
			<u-modal :show="createShow" title="创建权益卡" @confirm="createShow=false" confirmColor="#1682FF">
				<view slot="default" style="width: 100%">
					<u--text text="添加权益卡请联系业务员后台创建" size="32rpx" color="#3D3D3D" lineHeight="80rpx" align="center" />
				</view>
			</u-modal>
			<u-popup :show="qrShow" @close="qrShow =false" mode="center" closeable @open="open">
				<view class="qrBox">
					<u-image
						:src="baseSrc"
						width="320rpx" height="320rpx" mode="widthFix" />
					<u-text color="#777" size="28rpx" text="长按二维码识别|下载|分享" margin="36rpx 0 0" align="center" />
				</view>
			</u-popup>
			<u-datetime-picker :show="pickerShow" mode="datetime" v-model="startTime" @confirm="startTimeChange"
				@cancel="pickerShow = false"></u-datetime-picker>
			<u-datetime-picker :show="pickerShow2" mode="datetime" v-model="endTime" @confirm="endTimeChange"
				@cancel="pickerShow2 = false"></u-datetime-picker>
		</view>
	</z-paging>
</template>

<script>
	import {
		getSalesmanByPhone,
	} from "@/api/cardSalesman";
	import {
		equityCardTypeList,
		createEquityCardActivity,
		equityCardActivityTypeList
	} from "@/api/coupon";
	import { getMiniCodeByAppId , favorableActivityList} from "@/api/order.js";
	
	import {
		createActivity,
	} from "@/api/coupon.js";
	import {
		mapGetters
	} from "vuex";
	import moment from "moment";
	const dayStart = moment(
		new Date(new Date(new Date().toLocaleDateString()).getTime())
	);
	const dataEnd = moment(
		new Date(
			new Date(new Date().toLocaleDateString()).getTime() +
			24 * 60 * 60 * 1000 -
			1
		)
	);
	let customerId = "";
	export default {
		data() {
			return {
				appId: this.$appId,
				buttonCustomStyle: {
					width: "136rpx",
					height: "48rpx",
					fontSize: "26rpx"
				},
				tabList: [{
						name: "权益卡",
						id: 0,
					},
					{
						name: "活动记录",
						id: 1,
					},
				],
				currentTab: 0,
				dataList: [],
				statusBg: {
					1: "#78C997",
					6: "#A3ACE4",
					2: "#EFB791",
					4: "#efadda",
				},
				statusTitle: {
					2: "渠道活动",
					6: "线下印刷",
					4: "线上活动",
					1: "赠好友",
				},
				statusTime: {
					2: "转发时间：",
					6: "生成时间：",
					4: "结束时间：",
					1: "转发时间：",
				},
				statusSum: {
					2: "转发数量：",
					6: "印刷数量：",
					4: "活动数量：",
					1: "转发数量：",
				},
				show: false,
				show1: false,
				actionShow: false,
				offlineShow: false,
				onlineShow: false,
				createShow: false,
				phoneNum: "",
				numBer: "",
				userNamePhone: '',
				actionList: [{
						type: '2',
						name: '发给渠道'
					},
					{
						type: '6',
						name: '线下印刷'
					},
					{
						type: '4',
						name: '线上活动'
					},
					{
						type:'1',
						name: '送给好友'
					}
				],
				cardTypeId: '',
				changeType: '',
				cardTitle: '',
				offlineNum: '', //线下印刷数量
				pickerShow: false,
				pickerShow2: false,
				qrShow: false,
				startPicker: "",
				startSubmitTime: '',
				endSubmitTime: '',
				startTime: dayStart,
				endTime: dataEnd,
				onlineNum: '',
				baseSrc:''
			};
		},
		onShareAppMessage(res) {
			return {
				title: '微信小程序测试分享',
			}
		},
		created() {
			this.startPicker = Date.now();
		},
		methods: {
			qrCode(item){
				const params = {
				   page: "pages_benefitCard/card_management/active",
				   scene:item.uniqueId,
				   env_version: __wxConfig.envVersion,
				   check_path: false,
				   appId: this.appId,
				};
				getMiniCodeByAppId(params).then((res) => {
					if (res.code === 200 && res.data) {
					   var showImgData = res.data;
					   this.baseSrc = "data:image/png;base64," + showImgData;
					   this.qrShow = true
					}
				});
			},
			forward(item) {
				let url = item.fileUrl
				console.log(url,'俩1')
				uni.showLoading({
					title: '加载中'
				})
				uni.downloadFile({
					url: url, 
					success: function(res) {
						if (res.statusCode === 200) {
							uni.openDocument({
								filePath: res.tempFilePath,
								success: function(res) {
									console.log(res, '打开文件成功')
								},
								fail: (err) => {
									uni.showToast({
										title: '打开文件失败请重试',
										icon: 'none'
									})
								}
							})
						} else {
							uni.showToast({
								title: '打开文件失败请重试',
								icon: 'none'
							})
						}
						uni.hideLoading()
					},
					fail: (err) => {
						uni.hideLoading()
						uni.showToast({
							title: '加载失败请重试',
							icon: "none"
						})
					}
				})
			},



			// 线上活动
			onlineEdit() {
				this.onlineNum = "";
				this.onlineShow = false;
			},
			async onlineConfirm() {
				if (!this.startSubmitTime.length)
					return uni.showToast({
						title: "请选择开始时间",
						icon: "none",
					});
				if (!this.endSubmitTime.length)
					return uni.showToast({
						title: "请选择结束时间",
						icon: "none",
					});
				if (!this.onlineNum.trim().length || !/^[0-9]*$/.test(this.onlineNum))
					return uni.showToast({
						title: "请输入数量",
						icon: "none",
					});
				const params = {
					favorableId: this.cardTypeId,
					number: this.onlineNum,
					type: this.changeType,
					endTime: this.endSubmitTime,
					startTime: this.startSubmitTime,
					cardPackType:2
				};
				console.log(params, 'aa')
				let res = await createActivity(params);
				if (res.code === 200) {
					uni.$u.toast('创建线上活动成功');
					this.onlineEdit();
					this.$refs.paging.reload();
				}
			},
			startTimeChange(e) {
				const time =
					typeof e.value === "number" ? e.value : Date.parse(e.value);
				this.startSubmitTime = moment(time).format(
					"YYYY-MM-DD HH:mm:ss"
				);
				this.pickerShow = false;
			},
			endTimeChange(e) {
				const time =
					typeof e.value === "number" ? e.value : Date.parse(e.value);
				this.endSubmitTime = moment(time).format(
					"YYYY-MM-DD HH:mm:ss"
				);
				this.pickerShow2 = false;
			},

			to_shareEX(item) {
				uni.downloadFile({
					url: item.fileUrl,
					success: (res) => {
						uni.shareFileMessage({
							filePath: res.tempFilePath,
						})
					}
				})
			},
			selectClick(e) {
				console.log(e,'e')
				this.changeType = e.type
				this.actionShow = false;
				if (e.type == '2') return this.show = true;
				if (e.type == '6' || e.type == '1') return this.offlineShow = true;
				if (e.type == '4') return this.onlineShow = true;
			},
			cancelEdit() {
				this.phoneNum = "";
				this.show = false;
			},
			cancelEdit1() {
				this.show1 = false;
				this.numBer = "";
			},
			async confirmEdit() {
				if (
					!this.phoneNum.trim().length ||
					!/^1[3456789]\d{9}$/.test(this.phoneNum)
				)
					return uni.showToast({
						title: "请输入正确的手机号",
						icon: "none",
					});
				let {
					code,
					data
				} = await getSalesmanByPhone({
					phone: this.phoneNum,
				});
				if (code === 200 && data) {
					console.log("data :>> ", data);
					customerId = data.id;
					this.userNamePhone = `${data?.salesmanName ?? "微信用户"}  ${
			            data.mobile
			        }`;
					this.show1 = true;
				} else {
					uni.showToast({
						title: "请输入正确渠道手机号",
						icon: "none",
					});
				}
			},
			async confirmEdit1() {
				if (!this.numBer.trim().length || !/^[0-9]*$/.test(this.numBer))
					return uni.showToast({
						title: "请输入数量",
						icon: "none",
					});
				this.show1 = true;
				this.show = true;
				const params = {
					favorableId: this.cardTypeId,
					channelUserMobile: this.phoneNum,
					number: this.numBer,
					type: this.changeType,
					cardPackType:2
				};
				console.log(params)
				let res = await createActivity(params);
				if (res.code === 200) {
					uni.$u.toast('转发成功');
					this.cancelEdit();
					this.cancelEdit1();
					this.$refs.paging.reload();
				}
			},
			operate(item) {
				this.cardTypeId = item.id
				this.cardTitle = item.cardType
				this.actionShow = true;
			},
			// 线下印刷
			offlineEdit() {
				this.offlineNum = "";
				this.offlineShow = false;
			},
			async offlineConfirm() {
				if (!this.offlineNum.trim().length || !/^[0-9]*$/.test(this.offlineNum))
					return uni.showToast({
						title: "请输入数量",
						icon: "none",
					});
				if(this.changeType == 6){
					const params = {
						favorableId: this.cardTypeId,
						number: this.offlineNum,
						type: this.changeType,
						cardPackType:2
					};
					let res = await createActivity(params);
					uni.$u.toast('创建线下印刷成功');
					this.$refs.paging.reload();
				}else{
					uni.$u.route({
						url: "/pages_benefitCard/card_management/shareDetail",
						params: {
							title: this.cardTitle,
							cardTypeId: this.cardTypeId,
							number: this.offlineNum,
							type: this.changeType
						},
					});
					console.log('5得')
				}
				this.offlineEdit();
			},
			async tabChange(e) {
				this.currentTab = e.index;
				await this.$refs.paging.reload();
			},
			async queryList(pageNo, pageSize) {
				const that = this;
				let result;
				
				switch (this.currentTab) {
					case 0:
						const params = {
							pageNum: pageNo,
							pageSize: pageSize,
						};
						result = await equityCardTypeList(params);
						break;
					case 1:
						const params1 = {
							pageNum: pageNo,
							pageSize: pageSize,
							cardPackType:2
						};
						result = await favorableActivityList(params1);
				}
				that.$refs.paging.completeByTotal(result.data.rows, result.total);
			},
		},
	};
</script>

<style lang="scss" scoped>
	.topTabbar {
		background-color: #fff;
		padding-bottom: 16rpx;
	}

	.cellBox {
		width: 92vw;
		margin: 0 auto;

		::v-deep .u-cell {
			box-shadow: 0 0 12rpx 2rpx rgba(0, 0, 0, 0.08);
			margin-top: 32rpx;
			border-radius: 20upx;
		}

		::v-deep .u-cell__body {}
	}

	.fileBox {
		justify-content: flex-end;
		padding: 30rpx 20rpx 0 0;
	}

	.detail {
		width: 100%;
		box-sizing: border-box;
		border-radius: 20rpx;
		margin-top: 32rpx;
		background: #ffffff;

		&_title {
			width: 100%;
			padding: 26rpx 28rpx;
			box-sizing: border-box;
			position: relative;
		}
	}

	.cardbg {
		position: absolute;
		top: 0rpx;
		right: 0rpx;
		padding: 0 30rpx;
		border-radius: 0rpx 20rpx 0 20rpx;
		height: 48rpx;
		text-align: center;
		line-height: 48rpx;
		font-size: 36rpx;
		color: #1682FF;
		background-color: #EDF3FF;
	}

	.cardbgs {
		position: absolute;
		top: 26rpx;
		right: 0rpx;
		padding: 0 30rpx;
		border-radius: 28rpx 0 0 28rpx;
		height: 56rpx;
		text-align: center;
		line-height: 56rpx;
		font-size: 36rpx;
		color: #fff;
	}

	.timeBox {
		background: #F7F7F7;
		border-radius: 16rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		padding-left: 20rpx;
	}

	.btnBox {
		background: #1682ff;
		border-radius: 28rpx 28rpx 28rpx 28rpx;
		color: #ffffff;
		font-size: 26rpx;
		padding: 4rpx 40rpx;
	}

	.btnBox1 {
		border: 1rpx solid #1682ff;
		border-radius: 28rpx 28rpx 28rpx 28rpx;
		color: #1682ff;
		font-size: 26rpx;
		padding: 4rpx 40rpx;
		margin-right: 10rpx;
	}
	.qrBox{
		padding: 100rpx 60rpx 20rpx;
	}
</style>